<template>
  <div>
    <el-dialog v-bind="$attrs" v-on="$listeners" :visible.sync="showDialog" @open="onOpen" @close="onClose"
               title="修改用户">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData"  :rules="rules" size="medium" label-width="80px">
          <el-col :span="24">
            <!-- 用户头像 -->
            <el-form-item label="用户头像">

              <!-- 头衔缩略图 -->
              <pan-thumb :image="image"/>
              <!-- 文件上传按钮 -->
              <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
              </el-button>

              <!--
                v-show：是否显示上传组件
                :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                :url：后台上传的url地址
                @close：关闭上传组件
                @crop-upload-success：上传成功后的回调 -->
              <image-cropper
                v-show="imagecropperShow"
                :width="300"
                :height="300"
                :key="imagecropperKey"
                :url="'/upload'"
                field="file"
                @close="closeImage"
                @crop-upload-success="cropSuccess"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" placeholder="请输入密码" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="创建日期" prop="createDate">
              <el-date-picker
                v-model="formData.createDate"
                type="datetime"
                placeholder="选择日期时间">
                <el-input v-model="formData.createDate" placeholder="请输入创建日期" clearable :style="{width: '100%'}">
                </el-input>
              </el-date-picker>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-input v-model="formData.status" placeholder="请输入状态" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import ImageCropper from "../../components/ImageCropper/index";
  import PanThumb from "../../components/PanThumb/index";

  export default {
    name: "UserUpdate",
    components: {ImageCropper, PanThumb},

    // 接受父组件传递的值
    props: {
      uId: {type: String},
      updateVisible: {
        type: Boolean,
        default:
          false
      }
      ,
    }
    ,
    data() {
      return {
        formData: {
          uId: undefined,
          username: undefined,
          password: undefined,
          createDate: undefined,
          status: undefined
        },
        // 控制弹出框显示隐藏
        value1: '',
        showDialog: false,
        imagecropperShow: false, // 是否显示上传组件
        imagecropperKey: 0, // 上传组件id
        image: '',
        rules: {
          username: [{
            required: true,
            message: '请输入员工名称',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请选择部门编号',
            trigger: 'blur'
          }],

          uId: [{
            required: true,
            message: '请输入职位编号',
            trigger: 'change'
          }],
          createDate: [{
            required: true,
            message: '请输入员工编号',
            trigger: 'blur'
          }],
          status: [{
            required: true,
            message: '',
            trigger: 'blur'
          }]
        },
        field101Action: 'https://jsonplaceholder.typicode.com/posts/',
        field101fileList: [],
        sexOptions: [{
          "label": "帅哥",
          "value": 1
        }, {
          "label": "美女",
          "value": 2
        }],
      }
    }
    ,
    computed: {}
    ,
    watch: {
      // 监听 addOrUpdateVisible 改变
      updateVisible(oldVal, newVal) {
        this.showDialog = this.updateVisible;
        this.$axios.get("http://localhost:18080/api/sys/users/"+this.uId,this.formData).then((response) => {
          // console.log(this.eId)
          this.formData=response.data.data;
          this.image=response.data.data.imgUrl;
          // console.log(response);
        });
      }
    }
    ,
    created() {


    }
    ,
    mounted() {
    }
    ,
    methods: {

      onOpen() {

      }
      ,
      onClose() {
        this.$refs['elForm'].resetFields()
        this.$emit('changeShowUpdate', 'false')
      }
      ,
      close() {
        this.$emit('changeShowUpdate', 'false')
      },

      async handelConfirm() {
        this.$refs['elForm'].validate(valid => {
          if (!valid) return;
          console.log( this.formData.createDate)
          this.$axios.put("http://localhost:18080/api/sys/users/"+this.uId, this.formData).then((response) => {

            console.log(this.eId)
          });
          // this.onClose();
          location.reload()
        })
      }
      ,
      field101BeforeUpload(file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        let isAccept = new RegExp('image/*').test(file.type)
        if (!isAccept) {
          this.$message.error('应该选择image/*类型的文件')
        }
        return isRightSize && isAccept
      }
      ,
      // 上传成功后的回调函数
      cropSuccess(data) {
        console.log(data)
        var oldImg = this.image;
        this.imagecropperShow = false;
        this.image = data.data;
        this.formData.imgUrl=this.image;
        this.$axios.put("http://localhost:18080/api/sys/users/"+this.uId, this.formData).then((response) => {
          location.reload()
        });
        console.log(data.data);
        // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
        this.imagecropperKey = this.imagecropperKey + 1;
        this.deleteAvatar(oldImg);
      }
      ,

      // 关闭上传组件
      closeImage() {
        this.imagecropperShow = false
        // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
        this.imagecropperKey = this.imagecropperKey + 1
      }
      ,
      async deleteAvatar(oldImage) {
        const {data} = await deleteImgFile(oldImage);
        console.log(data);
      }
    }
  }
</script>

<style scoped>

</style>
